import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/layout'
import cart from '@/views/layout/cart'
import home from '@/views/layout/home'
import category from '@/views/layout/category'
import my from '@/views/layout/my'
import store from '@/store'

const login = () => import('@/views/login')
const order = () => import('@/views/order')
const pay = () => import('@/views/pay')
const prodetail = () => import('@/views/prodetail')
const search = () => import('@/views/search')
const searchList = () => import('@/views/search/list')
const myOrder = () => import('@/views/order/myorder')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: Layout,
      redirect: '/home',
      children: [
        { path: '/cart', component: cart },
        { path: '/home', component: home },
        { path: '/my', component: my },
        { path: '/category', component: category }]
    },
    { path: '/login', component: login },
    { path: '/order', component: order },
    { path: '/pay', component: pay },
    { path: '/prodetail/:id', component: prodetail },
    { path: '/search', component: search },
    { path: '/searchlist', component: searchList },
    { path: '/myorder', component: myOrder }
  ]
})

const authPage = ['/order', '/pay']

router.beforeEach((to, from, next) => {
  if (!authPage.includes(to.path)) {
    next()
  } else {
    if (store.getters.token) {
      console.log(store.getters.token)
      next()
    } else {
      next('/login')
    }
  }
})

export default router
